﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Shamrock.Helpers
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(IQueryable<T> source, int? pageIndex, int pageSize, bool showAll=false)
        {
            TotalCount = source.Count();
            PageSize = pageSize;
            TotalPages = TotalCount == 0 ? 1 : (int) Math.Ceiling(TotalCount/(double) PageSize);
            PageIndex = pageIndex ?? (TotalPages - 1);

            DisplayingAllPages = showAll;
            if (!showAll)
            {
                this.AddRange(source.Skip(PageIndex*PageSize).Take(PageSize));
            }
            else
            {
                this.AddRange(source);
            }

        }

        public bool DisplayingAllPages
        {
            get; private set;
        }

        public bool HasPreviousPage
        {
            get
            {
                return ((PageIndex > 0) && !DisplayingAllPages);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return ((PageIndex + 1 < TotalPages) && !DisplayingAllPages);
            }
        }
    }
}